package com.wg.net.protocols;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wg.core.io.IBinaryWriter;

import java.util.Arrays;

public class MessageHeaderConverterBinary implements IMessageHeaderConverter {
    private static final Log log = LogFactory.get();

    public static MessageHeaderConverterBinary getInstance() {
        return Singleton.INSTANCE.getManager();
    }

    @Override
    public MessageHeader parseHeader(byte[] data) {
        if (data.length > 1) {
            int num = data[0];
            MessageHeader header = new MessageHeader();
            header.setSizeInBytes(this.getHeaderSize());
            header.setZip((num & 128) == 128);
            header.setMessageType(MessageType.valueOf(num & 127));
            return header;
        }
        if (log.isDebugEnabled()) {
            log.debug("Failed to parse message header: {}", Arrays.toString(data));
        }
        return new MessageHeader();
    }

    @Override
    public void writeHeader(IBinaryWriter writer, MessageType messageType, boolean isZip) {
        byte num = messageType.getValue();
        if (isZip) {
            num = (byte) (num | 128);
        }
        writer.writeByte(num);
    }

    @Override
    public byte getHeaderSize() {
        return 1;
    }

    private enum Singleton {
        INSTANCE;
        MessageHeaderConverterBinary manager;

        Singleton() {
            this.manager = new MessageHeaderConverterBinary();
        }

        public MessageHeaderConverterBinary getManager() {
            return manager;
        }
    }
}
